//
//  ViewController.m
//  HZTrip
//
//  Created by WangChengwen on 10/8/14.
//  Copyright (c) 2014 hztrip.org. All rights reserved.
//

#import "HZTViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "DebugLog.h"
#import "HZTXferManager.h"
#import "HZTBikeStationManager.h"
#import "HZTStationInfo.h"
#import "JZLocationConverter.h"
#import "UMFeedback.h"
#import "UMSocial.h"
#include <math.h>
#import "Constants.h"
#import "UtilityDefinitions.h"

const double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
const double zoomLevel = 0.012;
/*
void bd_encrypt(double gg_lat, double gg_lon, double & bd_lat, double &bd_lon)
{
    double x = gg_lon, y = gg_lat;
    double z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi);
    double theta = atan2(y, x) + 0.000003 * cos(x * x_pi);
    bd_lon = z * cos(theta) + 0.0065;
    bd_lat = z * sin(theta) + 0.006;
}
*/



@interface MapAnnotation:NSObject <MKAnnotation>

@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@property (nonatomic, strong) HZTStationInfo *stationInfo;

@end


@implementation MapAnnotation

@end



@interface HZTViewController () <CLLocationManagerDelegate, MKMapViewDelegate, UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property(nonatomic, strong) CLLocationManager *locationManager;
@property(nonatomic, assign) CLLocationCoordinate2D currentCoordinate;
@property (nonatomic, strong) CLLocation *lastCenterLocation;
@property (weak, nonatomic) IBOutlet UIToolbar *toolbar;

@end

@implementation HZTViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    // 位置获取
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.delegate = self;
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    
    MKUserTrackingBarButtonItem *trackingItem = [[MKUserTrackingBarButtonItem alloc] initWithMapView:self.mapView];
    UIBarButtonItem *actionItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(shareToSNS:)];
    UIBarButtonItem *feedbackItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(sendFeedback:)];
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [self.toolbar setItems:@[flexibleSpace, trackingItem, flexibleSpace, actionItem, flexibleSpace, feedbackItem, flexibleSpace]];

    self.mapView.delegate = self;
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinishGetCircumInfo) name:kNotificationCircumInfoGetSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFailedGetCircumInfo) name:kNotificationCircumInfoGetFailed object:nil];

    [self.locationManager startUpdatingLocation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Actions

- (void)shareToSNS:(id)sender
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:nil
                                      shareText:@"小伙伴们，快来围观！我发现了杭州公共自行车的租用神器，界面简单，功能实用，快来一起安装吧。下载地址：http://www.hztrip.org"
                                     shareImage:nil
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, UMShareToSms, UMShareToEmail,nil]
                                       delegate:nil];
}

- (void)sendFeedback:(id)sender
{
    [UMFeedback showFeedback:self withAppkey:UMAppKey];
}


#pragma mark CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    if (locations.count > 0) {
        self.currentCoordinate = ((CLLocation *)locations[0]).coordinate;
        CLLocationCoordinate2D gcjCoordinate = [JZLocationConverter wgs84ToGcj02:_currentCoordinate];
        self.lastCenterLocation = [[CLLocation alloc] initWithLatitude:gcjCoordinate.latitude longitude:gcjCoordinate.longitude];
        [self.mapView setRegion:MKCoordinateRegionMake([JZLocationConverter wgs84ToGcj02:_currentCoordinate], MKCoordinateSpanMake(zoomLevel, zoomLevel)) animated:NO];
        CLLocationCoordinate2D bdCoordinate = [JZLocationConverter wgs84ToBd09:_currentCoordinate];
        [[HZTXferManager sharedManager] getCircumInfo:bdCoordinate.latitude longitude:bdCoordinate.longitude radius:0];
        [_locationManager stopUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"locationManager error = %@",error);
    // 将地图设置为杭州市，提示用户开启定位
    [self.mapView setRegion:MKCoordinateRegionMake(CLLocationCoordinate2DMake(30.273, 120.167), MKCoordinateSpanMake(0.12, 0.12)) animated:NO];

    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"打开“定位服务”以允许“杭州公共出行”使用您的位置" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alertView show];
        }
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请打开系统设置中的“隐私->定位服务”以允许“杭州公共出行”使用您的位置" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
    }
    else
    {
        [self.locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                [manager requestWhenInUseAuthorization];
            }
            break;
            
        default:
            break;
    }
}

#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    // 如果是当前位置，annotation的类型为MKUserLocation；否则为MapAnnotation
    if (![annotation isKindOfClass:[MapAnnotation class]]) {
        return nil;
    }
    
    NSString * pinReusableIdentifier = @"pinReusableIdentifier";//[MapAnnotation reusableIdentifierForPinColor:[UIColor redColor]];
    MKPinAnnotationView * annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinReusableIdentifier];
    if(annotationView == nil)
    {
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinReusableIdentifier];
        [annotationView setCanShowCallout:YES];
    }
    
    annotationView.annotation = annotation;
    annotationView.image = [UIImage imageNamed:@"Annotation"];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    annotationView.rightCalloutAccessoryView = button;
    
//    annotationView.opaque = NO;
//    annotationView.animatesDrop = NO;
//    annotationView.draggable = YES;
//    annotationView.selected = YES;
//    annotationView.calloutOffset = CGPointMake(15, 15);
    
    UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Annotation"]];
    annotationView.leftCalloutAccessoryView = imageView;
    
    return annotationView;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    NSLog(@"didSelectAnnotationView");

}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    // 显示租赁点详细信息
    HZTStationInfo *stationInfo = ((MapAnnotation *)view.annotation).stationInfo;
    NSString *message = [NSString stringWithFormat:@"编号：%@\n电话：%@\n 服务时间：%@\n 地址：%@", stationInfo.stationID, NONILString(stationInfo.telephone), stationInfo.serviceTime, stationInfo.address];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:view.annotation.title message:message delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
    [alertView show];
}


- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    CLLocationCoordinate2D gcjCoordinate = mapView.region.center;
    CLLocation *newLocation = [[CLLocation alloc] initWithLatitude:gcjCoordinate.latitude longitude:gcjCoordinate.longitude];
    // 当移动距离大于当前屏幕显示地图的0.3倍时，更新租赁点信息
    if (self.lastCenterLocation == nil || [self.lastCenterLocation distanceFromLocation:newLocation] > zoomLevel * 111000 * 0.3) {
        CLLocationCoordinate2D bdCoordinate = [JZLocationConverter gcj02ToBd09:mapView.region.center];
        [[HZTXferManager sharedManager] getCircumInfo:bdCoordinate.latitude longitude:bdCoordinate.longitude radius:0];
        self.lastCenterLocation = newLocation;
    }
}


#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL];
    }
}

#pragma mark CircumInfo
- (void)didFinishGetCircumInfo
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    for (NSString *key in [HZTBikeStationManager sharedManager].stationDictionary) {
        HZTStationInfo *stationInfo = [HZTBikeStationManager sharedManager].stationDictionary[key];
        MapAnnotation *annotation = [[MapAnnotation alloc] init];
        annotation.coordinate = [JZLocationConverter bd09ToGcj02:CLLocationCoordinate2DMake(stationInfo.latitude, stationInfo.longitude)];
        annotation.title = stationInfo.title;
        annotation.subtitle = [NSString stringWithFormat:@"可借数:%ld   可还数:%ld ", stationInfo.remainCount, stationInfo.totalCount-stationInfo.remainCount];
        annotation.stationInfo = stationInfo;
//        NSString *isAllDay = stationInfo.isAllDay?@"全天":@"非全天";
//        NSString *isOnDuty = stationInfo.isOnDuty?@"有人":@"无人";
        [self.mapView addAnnotation:annotation];
    }
}

- (void)didFailedGetCircumInfo
{
    
}
@end
